backgroundPage = chrome.extension.getBackgroundPage();

pageContext = backgroundPage.pageContext;

/*自定义字符串格式化*/
String.prototype.Format = function(args) {
    /*this代表要调用Format方法的字符串*/
    /*replace的第一个参数为正则表达式，g表示处理匹配到的所有字符串，在js中使用//包起来*/
    /*replace的第二个参数为匹配字符串的处理，k1匹配结果包含{}，k2只保留{}内的内容*/
    var temp = this.replace(/\{(\w+)\}/g,function(k1,k2) {
        console.log(k1,k2);
        /*replace将匹配到的k2用参数args替换后赋给新变量temp*/
        return args[k2];
    });
    /*自定义方法Format将格式化后的字符串返回*/
    return temp;
};

//js sql 解析器
window.JsSqlParser = function(sql) {
    var sql_keyword = [
        'insert',
        'update',
        'delete',
        'truncate',
        'select',
        'create',
        'drop',
        'alter',
    ];

    return {
        sql: sql,
        isSql: function() {
            var statement = this.statement();
            if (this.isEmpty(statement)) {
                return false;
            }
            return sql_keyword.indexOf(statement) >= 0;
        },

        handle: function(dbName) {
            var _sql = sql;
            var statement = this.statement();
            if (this.isEmpty(statement)) {
                return false;
            }
            tableList = this.getTable();
            for (var index in tableList) {
                _sql = _sql.replace(tableList[index],dbName + '.' + tableList[index]);
            }
            if (sql_keyword.indexOf(statement) >= 0 && statement == 'select') {
                return _sql;
            } else {
                return 'use ' + dbName + ';\n' + _sql;
            }
        },
        getTable: function() {
            var tableList = [];
            var testStr =
                "select * from t_recharge where recharge_no='91564562858860001'";
            var arr = ['from','insert\\s+into','join','update','table'];
            for (index in arr) {
                var rgex = new RegExp(
                    '\\s*' + arr[index] + '\\s+(\\b\\w+)?[\\r\\n\\s]*',
                    'gi'
                );
                var r = '';
                while ((r = rgex.exec(sql))) {
                    tableList.push(r[1]);
                }
            }
            console.log(JSON.stringify(tableList));
            return tableList;
        },
        statement: function() {
            var _sql = sql.trim();
            var length = _sql.length;
            var index = 0;
            for (;index < length;index++) {
                if (_sql[index] == ' ') {
                    return _sql.substr(0,index).toLowerCase().trim();
                }
            }
            return undefined;
        },
        isEmpty: function(obj) {
            if (typeof obj == 'undefined' || obj == null || obj == '') {
                return true;
            } else {
                return false;
            }
        },
    };
};

$(document).ready(function() {
    $('#instance_name').selectpicker();
        chrome.tabs.query({active: true,currentWindow: true},function(tab) {
        //获取当前tab
        chrome.tabs.sendMessage(
            tab[0].id,
            {action: 'getInstanceNameList'},
            function(response) {
                console.log('>>>>');
                if (response) {
                    $('#instance_name').empty();
                    $('#instance_name').append(response);
                    $('#instance_name').selectpicker('render');
                    $('#instance_name').selectpicker('refresh');
                }
                console.log(response);
            }
        );
    });
    // 实例变更获取数据库
    $('#instance_name').change(function() {
        //将数据通过ajax提交给获取db_name
        $('#db_name').empty();
        $('#db_name').prepend(
            '<option value="is-empty" disabled="" selected="selected">请选择数据库:</option>'
        );
        $('#db_name').selectpicker('render');
        $('#db_name').selectpicker('refresh');
        chrome.tabs.query({active: true,currentWindow: true},function(tab) {
            //获取当前tab
            chrome.tabs.sendMessage(
                tab[0].id,
                {
                    action: 'getDbNameList',
                    data: 'instance_name=' + $('#instance_name').val(),
                },
                function(response) {
                    console.log(response);
                    if ((response.callType = 'success')) {
                        var data = response.data;
                        if (data.status === 0) {
                            var result = data.data;
                            var dbs = [];
                            $('#db_name').empty();
                            for (var i = 0;i < result.length;i++) {
                                var name =
                                    '<option value="' +
                                    result[i] +
                                    '">' +
                                    result[i] +
                                    '</option>';
                                $('#db_name').append(name);
                                dbs.push({
                                    name: result[i],
                                    value: result[i],
                                    caption: result[i],
                                    meta: 'databases',
                                    score: '100',
                                });
                            }
                            $('#db_name').prepend(
                                '<option value="is-empty" disabled="" selected="selected">请选择数据库:</option>'
                            );
                            $('#db_name').selectpicker('render');
                            $('#db_name').selectpicker('refresh');
                        }
                    } else {
                        alert('数据加载失败');
                    }
                }
            );
        });
    });

    /*
    $('#db_name').change(function() {

        $('#db_table').empty();
        $('#db_table').prepend(
            '<option value="is-empty" disabled="" selected="selected">请选择表:</option>'
        );
        $('#db_table').selectpicker('render');
        $('#db_table').selectpicker('refresh');
        chrome.tabs.query({active: true,currentWindow: true},function(tab) {
            //获取当前tab
            chrome.tabs.sendMessage(
                tab[0].id,
                {
                    action: 'getTableNameList',
                    data: {
                        instance_name: $('#instance_name').val(),
                        db_name: $('#db_name').val(),
                    },
                },
                function(response) {
                    if ((response.callType = 'success')) {
                        var data = response.data;
                        if (data.status === 0) {
                            var result = data.data;
                            $('#db_table').empty();
                            for (var i = 0;i < result.length;i++) {
                                var name = '<option>' + result[i] + '</option>';
                                $('#db_table').append(name);
                            }
                            $('#db_table').prepend(
                                '<option value="is-empty" disabled="" selected="selected">请选择数据库:</option>'
                            );
                            $('#db_table').selectpicker('render');
                            $('#db_table').selectpicker('refresh');
                        }
                    }
                    console.log(response);
                }
            );
        });
    });
    */
    //表单验证
    function sqlquery_validate() {
        var result = true;
        var instance_name = $('#instance_name').val();
        var db_name = $('#db_name').val();
        var sqlContent = $('#sqlContent').val();
        if (sqlContent === null || sqlContent.trim() === '') {
            alert('SQL内容不能为空！');
            return (result = false);
        } else if (
            instance_name === null ||
            instance_name === $('#instance_name').attr('data-placeholder')
        ) {
            alert('请选择实例！');
            return (result = false);
        }
        return result;
    }
    //判断字符是否为空的方法
    function isEmpty(obj) {
        if (typeof obj == 'undefined' || obj == null || obj == '') {
            return true;
        } else {
            return false;
        }
    }
    $('#generateSql').click(function() {
        if (sqlquery_validate()) {
            var sqlContent = $('#sqlContent').val();
            var filterDbName = $('#filter_db_name').val();
            var dep = '';

            var _JsSqlParser = JsSqlParser(sqlContent);

            if (!_JsSqlParser.isSql()) {
                alert('不是sql,请填写sql语句');
                return;
            }

            $('#db_name option').each(function() {
                var dbName = $(this).val();
                if ('is-empty' != dbName) {
                    if (!isEmpty(filterDbName)) {
                        if (dbName.indexOf(filterDbName) >= 0) {
                            dep += _JsSqlParser.handle(dbName) + '\n';
                        }
                    } else {
                        dep += _JsSqlParser.handle(dbName) + '\n';
                    }
                }
            });
            $('#sqlOut').val(dep);
        }
    });
    $('#clear').click(function() {
        $('#sqlOut').val('');
    });

    var clipboard = new Clipboard('#copyFormat');
    clipboard.on('success',function(e) {
        alert('复制成功');
        e.clearSelection();
        console.log(e.clearSelection);
    });
    clipboard.on('error',function(e) {
        alert('复制失败');
        console.log(e.clearSelection);
    });
});
